package loengud.w11;

import java.net.*;
import java.io.*;

class HelloServer {

	@SuppressWarnings("resource")
	public static void main(String[] args) {

		args = new String[] {"9999"};
		int port = Integer.parseInt(args[0]);

		ServerSocket server;
		try {
			server = new ServerSocket(port);
		} catch (IOException ioe) {
			System.err.println("Couldn't run " + "server on port " + port);
			return;
		}
		while (true) {
			try {
				Socket connection = server.accept();
				ConnectionHandler handler = new ConnectionHandler(connection);
				new Thread(handler).start();
			} catch (IOException ioe1) {
				ioe1.printStackTrace();
			}
		}
	}
}

// Handles a connection of a client to an HelloServer.
// Talks with the client in the 'hello' protocol

class ConnectionHandler implements Runnable {

	// The connection with the client
	private Socket connection;

	public ConnectionHandler(Socket connection) {
		this.connection = connection;
	}

	public void run() {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));

			PrintWriter writer = new PrintWriter(new OutputStreamWriter(
					connection.getOutputStream()));

			String clientName = reader.readLine();

			writer.println("Hello " + clientName);
			writer.flush();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
